package com.yfree.activities;

import android.annotation.SuppressLint;
import android.app.Instrumentation;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.yfree.utils.YJSDelegate;
import com.yfree.utils.YJSDelegate2;
import com.yfree.views.YWebView2;

public abstract class YWebActivity2 extends YActivity {
    public YWebView2 webView;

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout(), canScrollFinish());
        webView = findWebView((ViewGroup) getWindow().getDecorView());
        WebSettings webSettings = webView.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setSavePassword(false);
        webSettings.setAppCacheEnabled(true);
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        webSettings.setAppCachePath(getApplication().getCacheDir().getAbsolutePath());
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        webView.loadUrl("file:///android_asset/" + getWebName());
        try {
            webView.addJavascriptInterface(Class.forName(getJSDelegate().getCanonicalName()).getConstructor(YActivity.class, YWebView2.class).newInstance(this, webView), getJSObjName());
        } catch (Exception ignored) {
        }
        webSettings.setJavaScriptEnabled(true);
        if (android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT && webView.getX5WebViewExtension() == null) {
            yShowBuilder("您的设备系统版本过低，部分功能可能会出现兼容性问题。\n请升级到安卓5.0或更高版本系统。", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            }, null, false);
            return;
        }
        if (enableAutoPlay())
            yRunOnTimer(new Runnable() {
                @Override
                public void run() {
                    Instrumentation inst = new Instrumentation();
                    inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, yDisplayMetrics.widthPixels / 2F, yDisplayMetrics.heightPixels / 2F, 0));
                    inst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, yDisplayMetrics.widthPixels / 2F, yDisplayMetrics.heightPixels / 2F, 0));
                }
            });
    }

    private YWebView2 findWebView(ViewGroup group) {
        if (group != null)
            for (int i = 0, j = group.getChildCount(); i < j; i++) {
                View child = group.getChildAt(i);
                if (child instanceof YWebView2) return (YWebView2) child;
                else if (child instanceof ViewGroup) {
                    YWebView2 result = findWebView((ViewGroup) child);
                    if (result != null) return result;
                }
            }
        return null;
    }

    public boolean enableAutoPlay() {
        return false;
    }

    public abstract int getLayout();

    public abstract String getWebName();

    public Class<? extends YJSDelegate2> getJSDelegate() {
        return YJSDelegate2.class;
    }

    public String getJSObjName() {
        return YJSDelegate.instance;
    }

    public boolean canScrollFinish() {
        return true;
    }

    public void yEvaluateScript(String script) {
        webView.loadUrl("javascript:" + script);
    }

    @Override
    public void onDestroy() {
        webView.getSettings().setJavaScriptEnabled(false);
        webView.stopLoading();
        webView.setVisibility(View.GONE);
        webView.clearHistory();
        webView.clearView();
        webView.removeAllViews();
        ((ViewGroup) webView.getParent()).removeView(webView);
        webView.destroy();
        try {
            ((ViewGroup) getWindow().getDecorView()).removeAllViews();
        } catch (Exception ignored) {
        }
        super.onDestroy();
    }
}